package com.originskyseed.platform.user.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.annotation.Resource;

import com.originskyseed.platform.user.mapper.*;
import com.originskyseed.platform.user.model.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.originskyseed.platform.common.api.util.QueryAppUtil;
import com.originskyseed.platform.common.utils.JsonUtils;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.tenant.util.TenantCodeUtil;
import com.originskyseed.platform.core.util.bean.PrimaryKeyGeneratorUtil;
import com.originskyseed.platform.user.service.IAnchorService;

/**
 * 主播信息Service接口实现类（OSI_ANCHOR）
 *
 * @author
 */
@DubboService
@Component("anchorService")
public class AnchorServiceImpl implements IAnchorService {

	private static final Logger logger = LoggerFactory.getLogger(AnchorServiceImpl.class);
	@Resource
	private AnchorMapper anchorMapper;

	@Resource
	private AnchorRelateCollectMapper anchorRelateCollectMapper;

	@Resource
	private DeptMapper deptMapper;

	@Resource
	private UserInfoMapper userInfoMapper;

	@Resource
	private AnchorGroupMapper anchorGroupMapper;

	@Resource
	private PlayerRelateConsumeMapper playerRelateConsumeMapper;

	@Resource
	private PlayerRelateViewLiveMapper playerRelateViewLiveMapper;

	/**
	 * 删除记录
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKey(String id) throws Exception {
		return this.anchorMapper.deleteByPrimaryKey(id);
	}

	/**
	 * 批量删除记录
	 *
	 * @param ids
	 * @return
	 * @throws Exception
	 */
	@Override
	public int deleteByPrimaryKeys(List<String> ids) throws Exception {
		return this.anchorMapper.deleteByPrimaryKeys(ids);
	}

	/**
	 * 插入记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insert(Anchor record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.anchorMapper.insert(record);
	}

	/**
	 * 插入记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertSelective(Anchor record) throws Exception {
		if (StringUtils.isBlank(record.getId())) {
			record.setId(PrimaryKeyGeneratorUtil.getInstance().getRandomKey());
		}
		record.setCreateTime(new Date());
		return this.anchorMapper.insertSelective(record);
	}

	/**
	 * 更新记录
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKey(Anchor record) throws Exception {
		record.setUpdateTime(new Date());
		return this.anchorMapper.updateByPrimaryKey(record);
	}

	/**
	 * 更新记录（仅非空值字段）
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public int updateByPrimaryKeySelective(Anchor record) throws Exception {
		record.setUpdateTime(new Date());
		return this.anchorMapper.updateByPrimaryKeySelective(record);
	}

	/**
	 * 根据主播Id查询主播信息详情
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public Anchor selectByAnchorId(String tenantCode,String id) throws Exception {
		if(tenantCode!=null&&StringUtils.isNotBlank(tenantCode))
		{
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		return  selectByAnchorId(id);
	}
	/**
	 * 根据主播Id查询主播信息详情
	 *
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@Override
	public Anchor selectByAnchorId(String id) throws Exception {
		Anchor anchor = this.anchorMapper.selectByAnchorId(id);
		/**
		 * 格式化身份证号和手机号显示
		 */
		if (anchor != null) {
			if (StringUtils.isNotBlank(anchor.getIdCardNum())) {
				String IdCardNumFat = anchor.getIdCardNum().replaceAll("(\\d{3})\\d{11}(\\d{4})", "$1****$2");
				anchor.setIdCardNum(IdCardNumFat);
			}
			if (StringUtils.isNotBlank(anchor.getPhone())) {
				String phoneFat = anchor.getPhone().replaceAll("(\\d{3})\\d{6}(\\d{2})", "$1****$2");
				anchor.setPhone(phoneFat);
			}
		}
		return anchor;
	}

	/**
	 * 查询主播信息（租户模式）
	 *
	 * @param id
	 * @param tenantCode
	 * @return
	 * @throws Exception
	 */
	@Override
	public Anchor selectByAnchorIdTenantCode(String id, String tenantCode) throws Exception {
		if (StringUtils.isNotEmpty(tenantCode)) {
			TenantCodeUtil.getInstance().createServerTenantCode(tenantCode);
		}
		return this.selectByAnchorId(id);
	}

	/**
	 * 查询列表
	 *
	 * @param record
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Anchor> selectList(Anchor record) throws Exception {
		return this.anchorMapper.selectList(record);
	}

	/**
	 * 分页查询列表
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<Anchor> selectListByPage(Map<String, Object> params, BasePage<Anchor> page) throws Exception {
		params.put("page", page);
		List<Anchor> list = this.anchorMapper.selectListByPage(params);
		page.setResults(list);
		return page;
	}

	/**
	 * 主播资料卡分页查询列表
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<Anchor> selectAnchorInFoListByPage(Map<String, Object> params, BasePage<Anchor> page, UserInfo userInfo) throws Exception {
		params.put("page", page);

		params.put("anchorIdList", getAnchorId(userInfo));
		// 查询的目的是为了搜索分页用的。
		List<Anchor> list = this.anchorMapper.selectAnchorInFoListByPage(params);

		String anchorIds = "";
		List<String> tempAnchorIdList = new ArrayList<>();
		if (list != null && list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				tempAnchorIdList.add(list.get(i).getAnchorId());
			}
		}
		if (tempAnchorIdList != null && tempAnchorIdList.size() > 0) {
			anchorIds = String.join(",", tempAnchorIdList);
		}
		List<Anchor> tempList = getAnchorList(anchorIds);
		if (tempList != null && tempList.size() > 0) {
			for (int i = 0; i < tempList.size(); i++) {
				Anchor anchor = tempList.get(i);
				getAnchorSign(anchor, list);
			}
		}
		page.setResults(tempList);
		return page;
	}

	/**
	 * 获取主播信息列表
	 * @param userInfo
	 * @return
	 * @throws Exception
	 */
	public List<String> getAnchorId(UserInfo userInfo) throws Exception
	{
		List<String> anchorIdList = new ArrayList<>();
		if (userInfo!=null&&userInfo.getType()!=null&&userInfo.getType() == 11) {
			if (StringUtils.isNotBlank(userInfo.getOtherAccount())) {
				anchorIdList.add(userInfo.getOtherAccount());
			}
		} else {
			Dept dept = this.deptMapper.selectByPrimaryKey(userInfo.getDeptId());
			if (dept != null) {
				List<String> deptIdList = new ArrayList<>();
				deptIdList.add(dept.getId());
				selectDeptSon(dept.getCode(), deptIdList);
				if (deptIdList != null && deptIdList.size() > 0) {
					anchorIdList = this.userInfoMapper.selectAnchorOtherAccountsByDeptIds(deptIdList);
				}
			}
		}
        return anchorIdList;
	}


	/**
	 *  分页查询 主播艺人薪资结算列表
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<Anchor> selectAnchorSalarySettlementByPage(Map<String, Object> params, BasePage<Anchor> page) throws Exception {
		params.put("page", page);
		List<Anchor> list = this.anchorMapper.selectAnchorSalarySettlementByPage(params);
		page.setResults(list);
		return page;
	}


	/**
	 *  查询 主播艺人薪资结算列表
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Anchor> selectAnchorSalarySettlementList(Map<String, Object> params) throws Exception {
		return this.anchorMapper.selectAnchorSalarySettlementList(params);
	}


	private Anchor getAnchorSign(Anchor anchor, List<Anchor> list) throws Exception {
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {
				Anchor tempAnchor = list.get(i);
				if (tempAnchor.getAnchorId().equals(anchor.getAnchorId())) {
					//查询主播是否在线
					int isOnLine = 1;//不在线
					TreeMap<String, Object> paramMap = new TreeMap<>();
					paramMap.put("anchorIds",tempAnchor.getAnchorId());
					/*Map resultMap = QueryAppUtil.query("anchorOnlineUrl", 1, paramMap);
					Integer code = Integer.parseInt(resultMap.get("code").toString());
					if (code == 1) {
						isOnLine = Integer.parseInt(resultMap.get("data").toString());
					} else {
						logger.error(resultMap.get("msg").toString());
					}*/
					anchor.setIsOnLine(isOnLine);
					anchor.setLocalId(tempAnchor.getLocalId() == null?"":tempAnchor.getLocalId());
					anchor.setLocalName(tempAnchor.getLocalName() == null?"":tempAnchor.getLocalName());
					anchor.setLocalAccount(tempAnchor.getLocalAccount() == null?"":tempAnchor.getLocalAccount());
					// String anchorSignName="";
					String id = tempAnchor.getAnchorSign();// 逗号分割
					StringBuffer anchorSignNames = new StringBuffer();
					StringBuffer anchorSignIds = new StringBuffer();
					if (id != null && StringUtils.isNotEmpty(id)) {
						List<String> array = Arrays.asList(id.split(","));
						if (array != null && array.size() > 0) {
							for (String signId : array) {
								AnchorGroup anchorGroup = this.anchorGroupMapper.selectByPrimaryKey(signId);
								String anchorSignName = anchorGroup == null ? "" : anchorGroup.getName();
								anchorSignNames.append(anchorSignName + ",");
								anchorSignIds.append(signId + ",");
							}
						}
						// AnchorGroup anchorGroup = this.anchorGroupMapper.selectByPrimaryKey(id);
						// anchorSignName=anchorGroup==null?"":anchorGroup.getName();
						anchor.setAnchorSignName(anchorSignNames.toString().substring(0, anchorSignNames.length() - 1));
						anchor.setAnchorSign(anchorSignIds.toString().substring(0, anchorSignIds.length() - 1));
						break;
					}
				}
			}
		}
		return anchor;
	}

	/**
	 * 主动查询主播列表信息
	 *
	 * @param anchorIds
	 * @return
	 * @throws Exception
	 */
	public List<Anchor> getAnchorList(String anchorIds) throws Exception {
		List<Anchor> anchorList = new ArrayList<>();
		if (anchorIds == null || StringUtils.isEmpty(anchorIds)) {
			return anchorList;
		}
		// 请求接口
		TreeMap<String, Object> paramMap = new TreeMap<>();
		paramMap.put("anchorIds", anchorIds);
		Map resultMap = QueryAppUtil.query("anchorInfoBatchUrl", 1, paramMap);
		if (resultMap != null) {
			Integer code = Integer.parseInt(resultMap.get("code").toString());
			String msg = (String) resultMap.get("msg");
			if (code == 1) {
				String data = (String) resultMap.get("data");
				anchorList = JsonUtils.parseArray(data, Anchor.class);
			} else {
				logger.error(msg);
			}
		}
		return anchorList;
	}

	/**
	 * 选择主播信息_分页查询列表
	 *
	 * @param params
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<TaskSelectAnchorVO> selectMaintainAnchorListByPage(Map<String, Object> params, BasePage<TaskSelectAnchorVO> page) throws Exception {
		params.put("page", page);
		List<TaskSelectAnchorVO> list = this.anchorMapper.selectMaintainAnchorListByPage(params);
		page.setResults(list);
		return page;
	}

	/**
	 * 导出Excel
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Anchor> selectListToExcel(Map<String, Object> params) throws Exception {
		BasePage<Anchor> page = new BasePage();
		page.setPageNo(1);
		page.setPageSize(999999);
		params.put("page", page);
		return this.anchorMapper.selectListByPage(params);
	}

	/**
	 * 主播广场_全平台主播信息_分页查询列表
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<Anchor> allPlatformAnchorListByPage(Map<String, Object> params, BasePage<Anchor> page, UserInfo userInfo) throws Exception {
		params.put("page", page);
		List<Anchor> list = this.anchorMapper.allPlatformAnchorListByPage(params);
		String userId = userInfo == null ? "" : userInfo.getId();
		for (int i = 0; i < list.size(); i++) {
			Anchor anchor = list.get(i);
			AnchorRelateCollect anchorRelateCollect = new AnchorRelateCollect();
			anchorRelateCollect.setAnchorId(anchor.getAnchorId());
			anchorRelateCollect.setIsDel(2);
			anchorRelateCollect.setBusinessId(userId);
			String anchorId = anchor.getAnchorId();

			// 请求接口
			TreeMap<String, Object> paramMap = new TreeMap<>();
			paramMap.put("anchorId", anchorId);
			Map resultMap = QueryAppUtil.query("anchorInfoUrl", 1, paramMap);
			if (resultMap != null) {
				Integer code = Integer.parseInt(resultMap.get("code").toString());
				String msg = (String) resultMap.get("msg");
				if (code == 1) {
					// json字符串转jsonObj
					String data = (String) resultMap.get("data");
					anchor = JsonUtils.parse(data, Anchor.class);
				} else {
					logger.error(msg);
				}
			}
			AnchorRelateCollect relateCollect = null;
			if (userId != null && StringUtils.isNotBlank(userId)) {
				relateCollect = this.anchorRelateCollectMapper.selectByAnchor(anchorRelateCollect);
			}
			if (relateCollect != null) {
				anchor.setIsMyCollect(1);
			} else {
				anchor.setIsMyCollect(0);
			}
			list.set(i, anchor);
		}
		page.setResults(list);
		return page;
	}

	/**
	 * 主播广场_我收藏的主播信息_分页查询列表
	 *
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	public BasePage<Anchor> myCollectAnchorListByPage(Map<String, Object> params, BasePage<Anchor> page) throws Exception {
		params.put("page", page);
		List<Anchor> list = this.anchorMapper.myCollectAnchorListByPage(params);
		page.setResults(list);
		return page;
	}

	/**
	 * 查询主播id是否存在
	 *
	 * @param anchorIds
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<String> selectAnchorIds(List<String> anchorIds) throws Exception {
		return this.anchorMapper.selectAnchorIds(anchorIds);
	}

	/**
	 * 批量插入记录
	 *
	 * @param list
	 * @return
	 * @throws Exception
	 */
	@Override
	public int insertBatchAnchor(List<Anchor> list) throws Exception {
		return this.anchorMapper.insertBatchAnchor(list);
	}

	/**
	 * 根据familyId查询记录
	 *
	 * @param familyId
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<Anchor> selectByFamilyId(String familyId) throws Exception {
		return this.anchorMapper.selectByFamilyId(familyId);
	}

	/**
	 * 统计主播观看人数和消费人数
	 * @throws Exception
	 */
	public void updateAnchorViewLiveAndConsume(String tenantCode)throws Exception{
		List<Anchor> anchorList = this.anchorMapper.selectList(new Anchor());
		for (Anchor anchor:anchorList) {
			if(StringUtils.isNotBlank(anchor.getAnchorId())){
				Integer consumeCount = this.playerRelateConsumeMapper.selectPlayerNumByAnchorId(anchor.getAnchorId());
				Integer viewLiveCount = this.playerRelateViewLiveMapper.selectPlayerNumByAnchorId(anchor.getAnchorId());
				Anchor updateAnchor = new Anchor();
				updateAnchor.setId(anchor.getId());
				updateAnchor.setConsumeCount(consumeCount);
				updateAnchor.setViewLiveCount(viewLiveCount);
				this.anchorMapper.updateByPrimaryKeySelective(updateAnchor);
			}
		}
	}


	/**
	 * 查询子集
	 *
	 * @param parentCode
	 * @param list
	 * @throws Exception
	 */
	private void selectDeptSon(String parentCode, List<String> list) throws Exception {
		List<Dept> deptList = this.deptMapper.selectByParentCode(parentCode);

		if (deptList != null) {
			for (Dept dept1 : deptList) {
				list.add(dept1.getId());
				selectDeptSon(dept1.getCode(), list);
			}
		}
	}
}
